<template>
  <div class="login-wrapper">
    <div class="login-box flex-center">
      <p class="title">云智AI——合作伙伴登录</p>

      <el-form
        :model="form"
        :rules="rules"
        label-width="60px"
        label-position="left">
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="form.mobile"
            placeholder="输入手机号"
            maxLength="11"
            @keyup.enter="loginFn" />
        </el-form-item>
        <el-form-item label="图形验证码" prop="code">
          <div class="form-content">
            <el-input
              v-model="form.code"
              placeholder="输入图形验证码"
              @input="verifycode"
              />
            <img :src="form.base64stringC" width="100" height="40" @click="getKaptchaImage" alt="" srcset="">
          </div>
        </el-form-item>
        <el-form-item label="短信验证码" prop="smsCode">
          <div class="form-content">
            <el-input
              v-model="form.smsCode"
              placeholder="请输入短信验证码"
              @keyup.enter="loginFn" />
            <el-button
              type="primary"
              :disabled="form.getverify"
              plain
              @click="getDynamicCode">
              获取短信验证码
            </el-button>
          </div>
        </el-form-item>

      </el-form>

      <el-button
        type="primary"
        class="btn"
        @click="loginFn">
        登录
      </el-button>
    </div>
  </div>
</template>

<script setup>
  import { GetKaptchaImage, sendRegisterVerifyCode, loginMobile } from '@/api/login';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  const router = useRouter();

  import { useUserStore } from '@/stores/user';
  const userStore = useUserStore();

  let form = ref({
    mobile: '',
    smsCode: '',
    code: '',
    base64stringC: '',
    idKeyC:'',
    getverify:true
  });

  /**
   * 定义表单验证规则
   * mobile: 手机号验证规则
   * - 第一个规则：使用正则表达式验证手机号格式是否正确
   * - 第二个规则：自定义验证函数，可用于额外的验证逻辑，例如远程校验
   */
  const rules = {
    mobile: [
      { 
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号',
        trigger: 'blur' // 触发验证的时机为失焦
      },
      {
        validator: (rule, value, callback) => {
          // 自定义验证逻辑，初始空值直接通过，否则可添加其他验证逻辑
          if (!value) {
            callback();
          } else {
            callback();
          }
        },
        trigger: 'blur' // 触发验证的时机为失焦
      }
    ]
  };

  function verifycode() {
    if (form.value.code.length) {
      form.value.getverify = false;
    }else {
      form.value.getverify = true;
    }
  }

  function getDynamicCode() {
    if (!form.value.mobile) {
      ElMessage.error('请输入手机号');
      return;
    }
    let data = {
      mobile: form.value.mobile,
      idKeyC: form.value.idKeyC,
      idValueC: form.value.code,
    }
    sendRegisterVerifyCode(data).then(res => {
      ElMessage.success('已发送，请注意查收');
    });
  }

async function getKaptchaImage() {
  try {
    const res = await GetKaptchaImage();

    if (res.code == 0) {
      form.value.base64stringC = res.data.base64stringC;
      form.value.idKeyC = res.data.idKeyC;
      return res;
    } else {
      ElMessage.error(res.msg);
      throw res; // 抛出异常以触发catch处理
    }
  } catch (err) {
    console.error('getKaptchaImage内部发生错误:', err);
  }
}

  function loginFn() {
    const { mobile, smsCode, code } = form.value;

    if (!mobile) {
      ElMessage.error('请输入手机号');
      return;
    }

    if (!smsCode) {
      ElMessage.error('请输入动态密码');
      return;
    }

    if (!code) {
      ElMessage.error('请输入验证码');
      return;
    }
    let data = {
      "idKeyC": form.value.idKeyC,
      "idValueC": form.value.code,
      "mobile": form.value.mobile,
      "smsCode": form.value.smsCode
    }
    loginMobile(data).then(res => {
      const { member, token } = res.data;
        userStore.setUser(member);
        localStorage.setItem('token', token);
        
        router.push({
          path: '/'
        });
    }).catch(err => {
      getKaptchaImage();
    });
  }

  onMounted(() => {
    getKaptchaImage();
  });
</script>

<style lang="scss" scoped>
  .login-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f0f2f5;

    .title {
      margin-bottom: 40px;
      font-size: 24px;
    }

    .login-box {
      flex-direction: column;
      padding: 40px;
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      .form-content {
        display: flex;
        align-items: center;

        .el-input {
          flex: 1;
          margin-right: 10px;
        }

        .code-text {
          text-align: center;
        }

        .text-code {
          width: 74px;
          letter-spacing: 4px;
        }
      }

      .btn {
        width: 140px;
        margin-top: 20px;
      }
    }
  }
</style>
